import $config from '@/config';
import $http from '@/utils/x-request';
import { complete } from '@/utils/x-promisify';

export default {
  namespaced: true,
  state: {
    scene: null,
    pendingList: {},
    // 是否显示我的界面中订阅消息浮层
    showMySubscription: false
  },
  mutations: {
    SET_DATA: (state, data) => {
      for (const key in data) {
        state[key] = data[key];
      }
    },
    PUSH_PENDING: (state, data) => {
      state.pendingList[data.url] = data;
    },
    REMOVE_PENDING: (state, data) => {
      delete state.pendingList[data.url];
    }
  },
  actions: {
    setData({ commit }, data) {
      return new Promise((resolve, reject) => {
        commit('SET_DATA', data);
        resolve();
      });
    },
    // 设置场景值
    setScene({ commit }, value) {
      return new Promise(async(resolve, reject) => {
        commit('SET_DATA', {
          scene: value
        });
        resolve();
      });
    },
    // 上报错误日志
    setAlarm({ commit, state }, options) {
      return new Promise(async(resolve, reject) => {
        const { code, url, requestData, header, message, time, profile, resHeader, resData } = options;
        const userInfo = uni.getStorageSync($config.userInfoName) || {};
        const { openId, unionId } = userInfo;
        // 获取当前page
        const scene = state.scene;
        const pages = getCurrentPages();
        const currPage = pages[pages.length - 1];
        const { route, options: query } = currPage;
        // 标记用户页面访问历史
        const history = pages.map(item => item.route);
        const systemInfo = uni.getSystemInfoSync(); // 设备系统信息
        const { networkType } = await complete(uni.getNetworkType)();
        $http({
          method: 'POST',
          timeout: 2000,
          url: `${$config.nodeApi}/api/v2/alarm/robot`,
          error: false,
          alarm: false,
          report: false,
          data: {
            code,
            message,
            time,
            header,
            history,
            networkType,
            route,
            query,
            scene,
            profile,
            resHeader,
            resData,
            openId,
            unionId,
            api: url,
            body: requestData,
            project: $config.project,
            appId: $config.appId,
            appName: $config.appName,
            appVersion: $config.appVersion,
            system: JSON.stringify(systemInfo)
          }
        }).then(() => {
          resolve();
        });
      });
    },
    // 全局拦截重复请求
    pushPending({ commit, state }, data) {
      return new Promise((resolve, reject) => {
        commit('PUSH_PENDING', data);
        resolve(state);
      });
    },
    // 全局拦截重复请求
    removePending({ commit, state }, data) {
      return new Promise((resolve, reject) => {
        if (state.pendingList[data.url] && data.cancel) {
          state.pendingList[data.url].cancel.abort(); // 执行取消操作
        } else if (state.pendingList[data.url]) {
          commit('REMOVE_PENDING', data);
        }
        // console.log(Object.keys(state.pending))
        resolve(state);
      });
    },
    // 获取服务器时间
    getTime() {
      return new Promise((resolve, reject) => {
        $http({
          timeout: 2000,
          url: `${$config.nodeApi}/api/v2/track/time`,
          method: 'get',
          login: false,
          report: false,
          error: false,
          alarm: false
        }).then((res) => {
          resolve(res);
        });
      });
    },
    // 缓存CPSID
    setCpsId({ commit }, options) {
      return new Promise(() => {
        $http({
          url: '/order/order/cps/id/save',
          method: 'POST',
          report: false,
          error: false,
          alarm: false,
          data: options
        });
      });
    },
    // 用户当日首次进去小程序
    setUserTheDay() {
      return new Promise((resolve) => {
        try {
          const storageTime = uni.getStorageSync('USER-THE-DAY');
          const time = new Date();
          let timeout = false;
          if (storageTime) {
            timeout = time.getDate() !== new Date(storageTime).getDate();
          }
          if (!storageTime || timeout) {
            uni.setStorageSync('USER-THE-DAY', +new Date());
            $http({
              url: '/account/user/entering/applet',
              method: 'POST',
              report: false,
              error: false,
              alarm: false
            }).then(() => {
              resolve();
            }).catch(() => {
              resolve();
            });
          } else {
            resolve();
          }
        } catch (e) {
          resolve();
        }
      });
    }
  }
};
